#!/usr/bin/env python
# -*- coding:utf-8 -*-
from conn.MyLogs import MyLogs
from members.MembersService import MembersService
from members.beans.MemberRewardHistoryObj import MemberRewardHistoryObj


# 数据日志型业务
# 功能包括,插入，查询
class MemberRewardHistoryService:
    std_array = {}
    conn = None
    membersService = None

    def __init__(self, conn):
        self.membersService = MembersService(conn)
        self.conn = conn

    # 日期，用户ID查询
    def fetch(self, param):
        try:
            count_sql = f" SELECT count(`id`) FROM `mem_member_reward_history` WHERE 1=1 %s"
            fetch_sql = f" SELECT {MemberRewardHistoryObj.to_string(True)}" \
                        f" FROM `mem_member_reward_history` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`member_id`,`create_date`) like CONCAT('%',\'{param['key']}\','%') "
            if len(param['member_id']) > 0:
                where_sql = where_sql + f" AND `member_id` = \'{param['member_id']}\'"
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])

            where_sql_no_limit = where_sql + f" ORDER BY `id` DESC"
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [MemberRewardHistoryObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, id):
        fetch_sql = f"SELECT {MemberRewardHistoryObj.to_string(True)} FROM `mem_member_reward_history` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [MemberRewardHistoryObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_history(self, pointHistory: object):
        try:
            self.membersService.update_member_point(pointHistory)
            insert_sql = f" INSERT INTO `mem_member_reward_history` ({MemberRewardHistoryObj.to_string(False)}) " \
                         " VALUES ( %s )" % MemberRewardHistoryObj.concat_datas(pointHistory)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}
